<template>
  <div class="search-history">
    <van-cell title="搜索历史">
      <template v-if="isDelete && historyList.length">
        <span @click="delAll">全部删除</span>&nbsp;&nbsp;&nbsp;
        <span @click="isDelete=false">完成</span>
      </template>
      <van-icon v-else @click="isDelete=true"  name="delete-o" />
    </van-cell>
    <!-- 列表 -->
    <van-cell v-for="(item,index) in historyList"
              @click="onClickHandler(item,index)"
              :key="item"
              :title="item">
      <van-icon v-if="isDelete" name="close" />
    </van-cell>
  </div>
</template>

<script>
import { setItem } from '@/utils/storage'
export default {
  name: 'SearchHistory',
  props: {
    // 历史记录
    historyList: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      isDelete: false // 是否处于删除状态
    }
  },
  methods: {
    // 删除所有
    delAll () {
      // this.historyList = [] // 错误的
      this.historyList.splice(0)
      setItem('TOUTIAO-SEARCH', this.historyList)
    },
    // 历史记录被点击
    onClickHandler (val, idx) {
      // 判断操作行为
      if (this.isDelete) {
        // 删除状态，删内容
        this.historyList.splice(idx, 1)
        setItem('TOUTIAO-SEARCH', this.historyList)
      } else {
        // 非删除，跳转
        this.$emit('search', val)
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
